#include "snake.h" 

Snake::Snake(Wall &wall, Food &food):wall(wall), food(food), pHead(NULL) {
    // 成员属性需要手动初始化
    // pHead = NULL;
}
void Snake::init_snake() {
    add_point(5, 5);
    add_point(6, 5);
    add_point(7, 5);
}
void Snake::add_point(int x, int y) {
    // 新节点
    Point *nPoint = new Point;
    nPoint->x = x;
    nPoint->y = y;
    nPoint->next = NULL;
    
    // 蛇头变为蛇身
    if (pHead != NULL) {
        wall.set_array(pHead->x, pHead->y, '=');
    }
    
    nPoint->next = pHead;
    pHead = nPoint;
    // 新节点为蛇头
    wall.set_array(pHead->x, pHead->y, '@');
}
void Snake::delete_point() {
    // 删除最后一个节点
    // 没有或只有头节点，不做操作
    if (pHead == NULL || pHead->next == NULL) return;
    Point *p_cur = pHead->next;
    Point *p_pre = pHead;
    while (p_cur->next != NULL) {
        p_pre = p_cur;
        p_cur = p_cur->next;
    }
    wall.set_array(p_cur->x, p_cur->y, ' ');
    delete p_cur;
    p_pre->next = NULL;
}
void Snake::destroy_point() {
    while(pHead != NULL) {
        Point *cur = pHead->next;
        delete pHead;
        pHead = cur;
    }
}
bool Snake::move(char key) {
    int x = pHead->x;
    int y = pHead->y;
    switch(key) {
        case UP:
            --y;
            break;
        case DOWN:
            ++y;
            break;
        case LEFT:
            --x;
            break;
        case RIGHT:
            ++x;
            break;
        default:
            return true;
            break;
    }
    char c = wall.get_array(x, y);
    if (c == '*' || c == '=') {
        cout<<"Game Over"<<endl;
        return false;
    }
    if (c == '#') {
        food.set_food();
    } else {
        delete_point();
    }
    add_point(x, y);
    return true;
}
